package com.scidpro;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ExportPgnToFileActivity extends Activity {

	public static final int SELECT_DIRECTORY = 1;

	public static final int FILE_ALREADY_EXIST_DIALOG = 1;

	private TextView filePathTextView;
	private Button selectFilePathButton;
	private EditText fileNameEditText;
	private Button setFileNameDateButton;
	private Button setFileNameGameInfoButton;
	private Button exportButton;

	private File currentDir;

	private SharedPreferences preferences;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.export_pgn_to_file);

		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		String lastPath = preferences.getString("path", null);

		final String filenameDate = (String) DateFormat.format("yyyyMMdd_kkmmss", new Date());
		final String filenameGameInfo = ((ScidApplication) getApplication()).getController().getFileName();

		if (lastPath == null) {
			currentDir = new File(Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY);
		} else {
			try {
				currentDir = new File(lastPath);
			} catch (Exception e) {
				currentDir = new File(Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY);
			}
		}

		filePathTextView = (TextView) findViewById(R.id.file_path);
		selectFilePathButton = (Button) findViewById(R.id.select_file_path_button);
		fileNameEditText = (EditText) findViewById(R.id.file_name);
		setFileNameDateButton = (Button) findViewById(R.id.set_file_name_date_button);
		setFileNameGameInfoButton = (Button) findViewById(R.id.set_file_name_game_info_button);
		exportButton = (Button) findViewById(R.id.export_button);

		fileNameEditText.setText(filenameGameInfo);
		filePathTextView.setText(currentDir.getAbsolutePath());

		setFileNameDateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				fileNameEditText.setText(filenameDate);
			}
		});
		setFileNameGameInfoButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				fileNameEditText.setText(filenameGameInfo);
			}
		});
		selectFilePathButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(ExportPgnToFileActivity.this, SelectFolderActivity.class);
				i.putExtra("path", currentDir.getAbsolutePath());
				startActivityForResult(i, SELECT_DIRECTORY);
			}
		});
		exportButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String pgn = ((ScidApplication) getApplication()).getController().getPGN();

				File pgnFile = new File(currentDir.getAbsoluteFile() + File.separator + fileNameEditText.getText().toString().trim() + ".pgn");

				if (pgnFile.exists()) {
					showDialog(FILE_ALREADY_EXIST_DIALOG);
				} else {
					if (!currentDir.exists()) {
						currentDir.mkdirs();
					}

					try {
						FileWriter fw = new FileWriter(pgnFile);
						fw.append(pgn);
						fw.flush();
						fw.close();

						Editor e = preferences.edit();
						e.putString("path", currentDir.getAbsolutePath());
						e.commit();

						Toast.makeText(ExportPgnToFileActivity.this, "File created", Toast.LENGTH_LONG).show();

						finish();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SELECT_DIRECTORY:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					String selectedPath = data.getStringExtra("path");
					currentDir = new File(selectedPath);
					filePathTextView.setText(currentDir.getAbsolutePath());
				}
			}
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case FILE_ALREADY_EXIST_DIALOG:
			return createMessageDialog("Attention", "Can't create file. File with this name is already exist.");
		}
		return null;
	}

	private AlertDialog createMessageDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(getString(android.R.string.ok), null);
		AlertDialog alert = builder.create();
		return alert;
	}

}
